package controllers;

import java.util.ArrayList;
import java.util.List;

import models.CategoryNode;
import dto.NodeDto;
import dto.TreeActionDto;
import play.mvc.Controller;

public class CategoryController extends Controller {
	
	public static void index() {
		
	}
	public static void createNewNode(long id, int position, String title,
			String type) {
		CategoryNode node = new CategoryNode();
		node.parentId = id;
		node.position = position;
		node.type = type;
		node.title = title;
		node.save();
		updateParentNode(id, false);
		renderJSON(TreeActionDto.success(node.id));
	}
	
	public static void removeNode(long id) {
		CategoryNode node = CategoryNode.find(id);
		node.delete();
		renderJSON(TreeActionDto.success());
	}
	
	public static void moveNode(long id, long ref, int position, int copy) {
		CategoryNode node = CategoryNode.find(id);
		
		List<CategoryNode> relNodes = CategoryNode.load(ref);
		if(relNodes != null && !relNodes.isEmpty()) {
			int maxPosition = relNodes.size();
			for (int i = position; i < maxPosition; i++) {
				CategoryNode oldNode = relNodes.get(i);
				oldNode.position = i + 1;
				oldNode.update();
			}
		}
		node.position = position;
		if(node.parentId != ref) {
			node.parentId = ref;
			updateParentNode(node.parentId, true);
			node.update();
			updateParentNode(ref, false);
		} else {
			
			node.update();
		}
		renderJSON(TreeActionDto.success());
	}
	
	public static void renameNode(long id, String title) {
		CategoryNode node = CategoryNode.find(id);
		node.title = title;
		node.update();
		renderJSON(TreeActionDto.success());
	}

	/**
	 * @param rel
	 */
	private static void updateParentNode(long ref, boolean moveOut) {
		List<CategoryNode> nodes = CategoryNode.load(ref);
		int size = 1;
		if(!nodes.isEmpty()) {
			size = nodes.size();
		}
		if(moveOut) {
			size = size -1;
		}
		CategoryNode relNode = CategoryNode.find(ref);
		relNode.left = relNode.position + 1;
		relNode.right = relNode.position + size + 2;
		relNode.update();
	}
	public static void getChildNode(long id) {
		List<NodeDto> nodeDtos = new ArrayList<NodeDto>();
		if (id == 0) {
			CategoryNode node = CategoryNode.find(1);
			
			if (node == null) {
				node = new CategoryNode();
				node.parentId = 0;
				node.left = 0;
				node.position = 0;
				node.right = 2;
				node.title = "Test 1";
				node.type = "drive";
				node.save();

			}
			System.out.println(">>>>>.node" + node.id);
			nodeDtos.add(NodeDto.convert(node));
			renderJSON(nodeDtos);
		} else {
			List<CategoryNode> nodes = CategoryNode.load(id);
		
			for (CategoryNode categoryNode : nodes) {
				System.out.println(">>>>.NodesLoop:" + nodes.size());
				nodeDtos.add(NodeDto.convert(categoryNode));
			}
			System.out.println(">>>>>>>>>>NodesAfter:" + nodeDtos.size());
			renderJSON(nodeDtos);
		}
	}
}
